<?php
/**
 * Created by PhpStorm.
 * User: Tso
 * Date: 2017/9/6
 * Time: 9:40
 */

namespace app\shop\controller;


use think\Controller;
use think\Db;
use think\Log;

class Delete extends Controller
{

    /**
     * 回收站自动清除
     */
    public function allDel()
    {
        $time = time() - 7 * 24 * 60 * 60;
        $album = Db::name('album')->where(array('status' => '-1','del_time'=>array('<',$time)))->select();
        $photo = Db::name('photo')->where(array('status' => '-1','del_time'=>array('<',$time)))->select();
        Db::startTrans();

        try {
            foreach ($photo as $key => $value) {
                $path = $_SERVER['DOCUMENT_ROOT'] . '/' . $value['img_url'];
                array_map("unlink", glob($path));
                if (!count(glob($path))) {

                    if (Db::name('photo')->where(array('id' => $value['id']))->delete()) {
                        //删除相册成功写入日志
                        Log::log('删除相片[' . $value['name'] . ']成功！');
                    } else {
                        //删除相册失败写入日志
                        Log::log('删除相片[' . $value['name'] . ']失败！');
                    }
                } else {
                    Log::log('删除文件[' . $path . ']失败！');
                }
            }
            foreach ($album as $k => $v) {
                if (!Db::name('photo')->where(array('album_id' => $v['id']))->count()) {
                    if (Db::name('album')->where(array('id' => $v['id']))->delete()) {
                        //删除相册成功写入日志
                        Log::log('删除相册[' . $v['name'] . ']成功！');

                    } else {
                        Log::log('删除相册[' . $v['name'] . ']失败！');
                    }

                }
            }
            Db::commit();
        } catch (\Exception $e) {

            Db::rollback();

            $this->error('删除失败！');

        }
    }

}